export const state = () => ({
  components: [],
  current: null,
  selectedDivider: null,
})

const attrs = require.context('@/components/ui/', false, /\.js$/)
const componentsAttrs = new Map()
attrs.keys().forEach((fileName) => {
  const componentName = fileName.slice(fileName.lastIndexOf('/') + 1, -3)
  const componentConfig = attrs(fileName)
  componentsAttrs.set(componentName, componentConfig.default)
})

function findNested(components, id) {
  for (let index = 0; index < components.length; index++) {
    const sec = components[index]
    if (sec.guid === id) {
      return {
        current: sec,
        index,
        components,
      }
    }
    if (!sec.children) {
      return { index: -1 }
    }
    const founded = findNested(sec.children, id)
    if (founded) {
      return founded
    }
    return {
      index: -1,
    }
  }
}

export const getters = {
  componentsAttrs: () => {
    return componentsAttrs
  },
  selectedSection: (state) => {
    const { current } = findNested(state.components, state.current)
    return current
  },
  getSection: (state) => (id) => {
    const { current } = findNested(state.components, id)
    return current
  },
}

export const mutations = {
  initComponent(state, components) {
    state.components = components
  },
  currentComponent(state, guid) {
    state.current = guid
  },
  addComponent(state, component) {
    state.components.push(component)
  },
  removeComponent(state, guid) {
    const { index, components } = findNested(state.components, guid)
    if (index > -1) {
      components.splice(index, 1)
      state.current = ''
    }
  },
  updateComponents(state, components) {
    state.components = [...components]
  },
  updateProps(state, props) {
    const { index, components } = findNested(state.components, state.current)
    components[index].props = props
  },

  updateDivider(state, props) {
    state.selectedDivider = props
  },
}
